#include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include <ctime>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

int main(int argc, char **argv)
{

    // 获取服务器IP地址和端口号
    const char *server_ip = "192.168.1.138";
    std::string strFileName = "a.txt";

    if (argc == 2)
    {
        strFileName = argv[1];
    }

    int server_port = 9527;

    // 创建socket
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        printf("socket error\n");
        return -1;
    }

    // 连接服务器
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(server_port);
    serverAddr.sin_addr.s_addr = inet_addr(server_ip);
    int ret = connect(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
    if (ret == -1)
    {
        printf("connect error\n");
        return -1;
    }

    // 发送文件名和文件大小
    FILE *file = fopen(strFileName.c_str(), "rb");
    if (file == NULL)
    {
        perror("fopen error");
        return -1;
    }
    fseek(file, 0, SEEK_END);
    int file_size = ftell(file);
    fseek(file, 0, SEEK_SET);



    
    printf("file_name = %s\n", strFileName.c_str());
    write(fd, strFileName.c_str(), strFileName.size());


    printf("file_size = %d\n", file_size);
    std::string strFileSize = std::to_string(file_size);
    write(fd, strFileSize.c_str(), strFileSize.size());

    usleep(500);

    // 发送文件内容
    char buffer[1024] = {0};
    int bytes_sent = 0;
    while (bytes_sent < file_size)
    {
        int n = fread(buffer, 1, sizeof(buffer), file);
        if (n <= 0)
        {
            break;
        }
        write(fd, buffer, n);
        bytes_sent += n;
        printf("this time send %d Bytes, total %d\n", n, bytes_sent);
        usleep(300);
    }

    // 关闭文件和socket
    fclose(file);
    close(fd);

    return 0;
}
